package org.ioc.com.captchademo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.ioc.com.captchademo.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    public final static long valid_session_timeout=60*1000;

    @RequestMapping("/get")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());
        lineCaptcha.write(response.getOutputStream());
        String code = lineCaptcha.getCode();
        session.setAttribute(captchaProperties.getSession().getKey(),code);
        session.setAttribute(captchaProperties.getSession().getDate(),new Date());
    }
    @RequestMapping("/check")
    public Boolean check(String inputcode,HttpSession session){
        if (!StringUtils.hasLength(inputcode)){
            return false;
        }
        String saveCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate= (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if (inputcode.equalsIgnoreCase(saveCode)){
            if (saveDate!=null&&System.currentTimeMillis()-saveDate.getTime()<valid_session_timeout){
                return true;
            }

        }
        return false;
    }
}
